<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogFormVisible"
    width="500px"
    @close="close"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="类别名称" prop="category_name">
        <el-input v-model="form.category_name" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="save">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { doAdd, doEdit } from '@/api/supplierCategory'

  export default {
    name: 'SupplierCategoryEdit',
    data() {
      return {
        form: {
          category_name: '',
        },
        rules: {
          category_name: [
            {
              required: true,
              trigger: 'blur',
              message: '请输入供应商分类名称',
            },
          ],
        },
        title: '',
        dialogFormVisible: false,
        type: '',
      }
    },
    created() {},
    methods: {
      showEdit(row) {
        if (!row) {
          this.title = '添加'
          this.type = 'add'
        } else {
          this.title = '编辑'
          this.type = 'edit'
          this.form = Object.assign({}, row)
        }
        this.dialogFormVisible = true
      },
      close() {
        this.$refs['form'].resetFields()
        this.form = this.$options.data().form
        this.dialogFormVisible = false
      },
      save() {
        this.$refs['form'].validate(async (valid) => {
          if (valid) {
            let msg
            if (this.type === 'add') msg = await doAdd(this.form)
            else
              msg = await doEdit({
                ...this.form,
                supplier_category_id: this.form.id,
              })
            this.$baseMessage(msg, 'success')
            this.$emit('fetch-data')
            this.close()
          } else {
            return false
          }
        })
      },
    },
  }
</script>
